package com.booter.zookeeper.serializer;

import java.io.InputStream;

public class UnsafeByteArrayInputStream extends InputStream {

    protected byte[] buf;

    protected int pos;

    protected int mark;

    protected int count;
    //private Object o = new Object();

    public UnsafeByteArrayInputStream(byte buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

    public UnsafeByteArrayInputStream(byte buf[], int offset, int length) {
        this.buf = buf;
        this.pos = offset;
        this.count = Math.min(offset + length, buf.length);
        this.mark = offset;
    }

    @Override
    public int read() {
        return this.pos < this.count ? this.buf[this.pos++] & 0xff : -1;
    }

    @Override
    public int read(byte[] b, int off, int len) {
        if (b == null) {
            throw new IllegalArgumentException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        }

        if (this.pos >= this.count) {
            return -1;
        }

        int avail = this.count - this.pos;
        if (len > avail) {
            len = avail;
        }
        if (len <= 0) {
            return 0;
        }
        System.arraycopy(this.buf, this.pos, b, off, len);
        this.pos += len;
        return len;
    }

    @Override
    public long skip(long n) {
        long k = this.count - this.pos;
        if (n < k) {
            k = n < 0 ? 0 : n;
        }

        this.pos += k;
        return k;
    }

    @Override
    public int available() {
        return this.count - this.pos;
    }

    @Override
    public boolean markSupported() {
        return true;
    }

    @Override
    public synchronized void mark(int readAheadLimit) {//NOPMD
        this.mark = this.pos;
    }

    @Override
    public synchronized void reset() {//NOPMD
        this.pos = this.mark;
    }

}
